package com.basic.library.utils

import android.animation.ValueAnimator
import android.view.View
import android.view.ViewGroup

/**
 * @author yj
 * @description
 */
class AnimationUtil {

    var height = 0 //折叠view的初始高度(必须)

    fun expandable(view: View) {
        if (height == 0) height = view.height
        if (view.visibility == View.VISIBLE) {
            collapse(view)
        } else {
            expand(view)
        }
    }

    fun collapse(view: View) {
        val expanded = view.visibility == View.VISIBLE
        val va = ValueAnimator.ofFloat(0f, 1f)
        va.setTarget(view)
        va.duration = 250
        va.addUpdateListener {
            val lp = view.layoutParams
            lp.height = (height * (1 - it.animatedFraction)).toInt()
            if (lp.height == 0) {
                view.visibility = View.GONE
            } else {
                view.layoutParams = lp
            }
        }
        va.start()
//    val oa = ObjectAnimator.ofFloat(View(view.context), "alpha", if (expanded) 1f else 0f)
//    oa.duration = 250
//    oa.addUpdateListener {
//        val lp = view.layoutParams
//        lp.height = (height * (1 - it.animatedFraction)).toInt()
//        println("${it.animatedValue} - ${it.animatedFraction}  -  ${lp.height}")
//        view.layoutParams = lp
//    }
//    oa.start()
    }

    fun expand(view: View) {
        val va = ValueAnimator.ofFloat(0f, 1f)
        view.visibility = View.VISIBLE
        val lp = view.layoutParams
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT
        view.layoutParams = lp
        println("-----${view.height}")
        va.setTarget(view)
        va.duration = 250
        va.addUpdateListener {
            val lp = view.layoutParams
            lp.height = (height * it.animatedFraction).toInt()
            if (lp.height == 0)
                lp.height = 1
            view.layoutParams = lp
        }
        va.start()
    }
}